package com.qi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qi.entity.Role;
import com.qi.entity.User;
import com.qi.mapper.RoleMapper;
import com.qi.mapper.UserMapper;
import com.qi.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qi.vo.query.RoleQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dingchunlin
 * @since 2024-03-15
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户查询角色列表
     *
     * @param page
     * @param roleQueryVo
     * @return
     */
    @Override
    public IPage<Role> findRoleListByUserId(IPage<Role> page, RoleQueryVo roleQueryVo) {
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //角色名称
        lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(roleQueryVo.getRoleName()),Role::getRoleName,roleQueryVo.getRoleName());
        //进行排序
        lambdaQueryWrapper.orderByAsc(Role::getId);
        //根据用户ID查询用户信息
        User user = userMapper.selectById(roleQueryVo.getUserId());
        //如果用户不为空、且不是管理员，则只能查询自己创建的角色
        if(user!=null && !ObjectUtil.isEmpty(user.getIsAdmin()) &&
                user.getIsAdmin() !=1){
            lambdaQueryWrapper.eq(Role::getCreateUser,roleQueryVo.getUserId());
        }
        return roleMapper.selectPage(page,lambdaQueryWrapper);
    }

    /**
     * 保存角色权限关系
     *
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Override
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds) {
        //删除该角色对应的权限信息
        baseMapper.deleteRolePermission(roleId);
        //保存角色权限
        return baseMapper.saveRolePermission(roleId,permissionIds) > 0;
    }

    /**
     * 检查角色下面是否存在用户
     *
     * @param id
     * @return true：表示没有用户，false：表示有用户
     */
    @Override
    public boolean checkRole(Long id) {
        Integer result = roleMapper.checkRole(id);
        if (result == 0 ){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 根据用户ID查询该用户拥有的角色ID
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> findRoleIdByUserId(Long userId) {
        return roleMapper.findRoleIdByUserId(userId);
    }
}
